import type { ConstructorOf, DictionaryImpl } from "../declarations";

/**
 * - 作者: DoooReyn
 * - 日期: 2023.10.29
 * - 名称: Dict
 * - 描述: 字典
 */
export class Dictionary<T> implements DictionaryImpl<T> {
    /** 字典存储对象 */
    protected _dict: Record<string, T>;

    public constructor() {
        this._dict = {};
    }

    public get size() {
        return Object.keys(this._dict).length;
    }

    public has(key: string) {
        return this._dict[key] !== undefined;
    }

    public fetch(key: string): T | undefined {
        return this._dict[key];
    }

    public get(key: string, type: ConstructorOf<T>): T | undefined {
        const asset = this._dict[key];
        if (asset !== undefined && asset instanceof type) {
            return asset;
        }
        return undefined;
    }

    public add(key: string, value: T): T {
        this._dict[key] = value;
        return value;
    }

    public remove(key: string) {
        delete this._dict[key];
    }

    public each(fn: (key: string, value: T) => void) {
        Object.keys(this._dict).forEach((v) => fn(v, this._dict[v]));
    }

    public when(fn: (key: string, value: T) => boolean) {
        const keys = Object.keys(this._dict);
        for (const key of keys) {
            if (fn(key, this._dict[key])) {
                break;
            }
        }
    }

    public clear() {
        Object.keys(this._dict).forEach((v) => delete this._dict[v]);
    }
}
